<template>
  <ToolbarButton
    type="dropdown"
    icon="i-tabler-crop"
    title="纸张大小"
    dropdown-icon="i-ri-arrow-down-s-fill"
    popover-width="280px"
    popover-placement="bottom-start"
    :large-icon="props.largeIcon"
    :hide-text="props.hideText"
    @main-click="togglePageSize"
  >
    <template #dropdown>
      <div class="page-size-dropdown">
        <!-- 纸张大小选项 -->
        <div class="page-size-options">
          <div
            v-for="(size, index) in availablePageSizes"
            :key="index"
            class="page-size-option"
            :class="{ active: currentPageSize === size }"
            @click="setPageSize(size)"
          >
            <!-- 选中标记 -->
            <div class="page-size-check">
              <i
                v-if="currentPageSize === size"
                class="i-ri-check-line"
              ></i>
            </div>
            <!-- 选项信息 -->
            <div class="page-size-info">
              <div class="size-label">{{ getPageSizeLabel(size) }}</div>
              <div class="size-values">
                {{ formatSize(size) }}
              </div>
            </div>
          </div>
        </div>
        <!-- 自定义纸张大小按钮 -->
        <div class="page-size-custom-wrapper">
          <div class="page-size-custom" @click="handleCustomSize">
            <i class="i-ri-settings-3-line"></i>
            <span>自定义纸张大小</span>
          </div>
        </div>
      </div>
    </template>
  </ToolbarButton>

  <!-- 页面设置弹窗 -->
  <PageSettings
    v-model="showPageSettings"
    :page-sizes="editorProps?.dicts?.pageSizes"
    default-tab="paper"
  />
</template>

<script setup lang="ts">
import { inject, computed, ref, type Ref } from "vue";
import type { PageOption, EditorProps, PageSize } from "../../../../types";
import ToolbarButton from "../../../button/index.vue";
import PageSettings from "./PageSettings.vue";
import { closeAllToolbarPopups } from "../../../button/src/utils/toolbarPopupManager";

defineOptions({
  name: "PageSize",
});

const props = withDefaults(
  defineProps<{
    largeIcon?: boolean;
    hideText?: boolean;
  }>(),
  {
    largeIcon: false,
    hideText: true,
  }
);

// 注入页面配置和编辑器配置
const pageOptions = inject<Ref<PageOption>>("page");
const editorProps = inject<EditorProps>("editorProps");

// 页面设置弹窗显示状态
const showPageSettings = ref(false);

// 获取可用的纸张大小选项（排除自定义选项）
const availablePageSizes = computed(() => {
  return (editorProps?.dicts?.pageSizes || []).filter(
    (size) => size.width !== 0 || size.height !== 0
  );
});

// 获取页面尺寸标签
const getPageSizeLabel = (size: PageSize): string => {
  const label = size.label;
  return typeof label === "string" ? label : label.zh_CN || label.en_US || "";
};

// 格式化尺寸显示
const formatSize = (size: PageSize): string => {
  if (size.width === 0 && size.height === 0) {
    return "自定义";
  }
  return `${size.width}厘米 x ${size.height}厘米`;
};

// 检查当前页面大小是否匹配某个选项
const isPageSizeEqual = (
  size1: PageSize,
  size2: { width: number; height: number; label?: any }
): boolean => {
  if (!size1 || !size2) return false;
  // 比较原始尺寸（不考虑方向）
  return (
    Math.abs(size1.width - size2.width) < 0.01 &&
    Math.abs(size1.height - size2.height) < 0.01
  );
};

// 当前选中的纸张大小
const currentPageSize = computed(() => {
  if (!pageOptions?.value?.size) return null;
  const currentSize = pageOptions.value.size;
  return availablePageSizes.value.find((size) =>
    isPageSizeEqual(size, currentSize)
  );
});


// 切换纸张大小（主按钮点击）
const togglePageSize = () => {};

// 设置纸张大小
const setPageSize = (size: PageSize) => {
  if (!pageOptions?.value) return;

  // 创建新对象，避免污染原始数据
  pageOptions.value.size = {
    label: size.label,
    width: size.width,
    height: size.height,
  };
  
  // 关闭 dropdown 弹窗
  closeAllToolbarPopups(undefined, undefined, ["select", "popover"]);
};

const handleCustomSize = () => {
  // 关闭 dropdown 弹窗
  closeAllToolbarPopups(undefined, undefined, ["select", "popover"]);
  // 打开页面设置弹窗
  showPageSettings.value = true;
};
</script>

<style lang="scss" scoped>
.page-size-dropdown {
  padding: 8px;
  max-height: 400px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.page-size-options {
  display: flex;
  flex-direction: column;
  gap: 4px;
  overflow-y: auto;
  overflow-x: hidden;
  flex: 1;
  min-height: 0;
  max-height: 320px;
  
  /* 自定义滚动条样式 */
  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-track {
    background: transparent;
    border-radius: 3px;
  }

  &::-webkit-scrollbar-thumb {
    background: var(--editor-scrollbar-thumb-color, rgba(0, 0, 0, 0.2));
    border-radius: 3px;
    transition: background 0.2s ease;

    &:hover {
      background: var(--editor-scrollbar-thumb-hover-color, rgba(0, 0, 0, 0.3));
    }
  }
}

.page-size-option {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 8px;
  cursor: pointer;
  transition: all 0.2s ease;

  &:hover {
    background-color: color-mix(
      in srgb,
      var(--editor-primary-color) 4%,
      transparent
    );
  }

  &.active {
    background-color: color-mix(
      in srgb,
      var(--editor-primary-color) 8%,
      transparent
    );
  }
}

.page-size-check {
  flex-shrink: 0;
  width: 16px;
  height: 16px;
  display: flex;
  align-items: center;
  justify-content: center;

  .i-ri-check-line {
    font-size: 16px;
    color: var(--editor-primary-color, #0D61F2);
    transition: color 0.2s ease;
  }
}


.page-size-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 2px;
  min-width: 0;
}

.size-label {
  font-size: 14px;
  font-weight: 700;
  color: var(--editor-text-color);
  line-height: 1.5;
}

.size-values {
  font-size: 12px;
  color: var(--editor-text-color-light);
  line-height: 1.4;
}

.page-size-custom-wrapper {
  flex-shrink: 0;
  padding-top: 4px;
  border-top: 1px solid var(--editor-border-color);
}

.page-size-custom {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  color: var(--editor-text-color);

  i {
    font-size: 16px;
    color: var(--editor-text-color);
    transition: color 0.2s ease;
  }

  span {
    font-size: 14px;
  }

  &:hover {
    background-color: color-mix(
      in srgb,
      var(--editor-primary-color) 4%,
      transparent
    );
    color: var(--editor-primary-color);

    i {
      color: var(--editor-primary-color);
    }
  }
}

/* 暗色主题适配 */
[theme-mode="dark"] {
  .page-size-option {
    &:hover {
      background-color: color-mix(
        in srgb,
        var(--editor-primary-color) 4%,
        transparent
      );
    }
  }


  .page-size-custom {
    color: var(--editor-text-color);
    border-color: var(--editor-border-color);

    i {
      color: var(--editor-text-color);
    }

    &:hover {
      background-color: color-mix(
        in srgb,
        var(--editor-primary-color) 4%,
        transparent
      );
      color: var(--editor-primary-color);

      i {
        color: var(--editor-primary-color);
      }
    }
  }
}
</style>

